IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_TemplateSave]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_TemplateSave]
GO
CREATE procedure [dbo].[cms_sp_TemplateSave]
(
	@TemplateId int,
	@SiteId int = null,
	@SiteGroupId int = null,
	@TemplateName nvarchar(250),
	@TemplateUrl nvarchar(250),
	@TemplateTypeKey int,
	@IsDefault bit,
	@LastUpdatedBy int,
	@DateLastUpdated datetime,
	@TemplateRegions varchar(8000) = null,
	@TemplareRegionDelimiter nvarchar(5) = null,
	@DefaultRegionId int = null
)
as
if @IsDefault = 1
begin
	update dbo.Templates
		set IsDefault = 0
end
update dbo.Templates
set 
	SiteId = @SiteId,
    SiteGroupId = @SiteGroupId,
    TemplateName = @TemplateName,
    TemplateUrl = @TemplateUrl,
    TemplateTypeKey = @TemplateTypeKey,
    LastUpdatedBy = @LastUpdatedBy,
    DateLastUpdated = @DateLastUpdated,
    IsDefault = @IsDefault,
    DefaultRegionId = @DefaultRegionId
where TemplateId = @TemplateId
if @TemplateRegions is not null
begin
	insert into dbo.TemplateRegions
	(
	TemplateId,
	TemplateRegionName
	)
	select 	
		@TemplateId,
		tmp.part	
	from dbo.cms_udf_SplitString(@TemplateRegions, @TemplareRegionDelimiter) as tmp
	where not tmp.part in (select tr.TemplateRegionName from TemplateRegions tr where tr.TemplateId = @TemplateId)
end


GO

